﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using Microsoft.Practices.Unity;
using Web.SystemLogin.Services;
using Web.SystemLogin.Models;
using Web.SystemLogin.Business;
using System.Web.Security;
using Web.SystemLogin.ServiceContract;
using System.Data;
using DreamBuilder.Common;
using Common;
using DreamBuilder.Core.Container;
using DreamBuilder.Core.Log;
using CommonModule;

namespace Web.Views.SystemLogin
{
    public partial class OcsLogin : PageBase
    {
        [Dependency]
        public ISystemLogin SystemLoginComponent
        {
            get;
            set;
        }

        public String StringParam = "?";

        protected void Page_Load(object sender, EventArgs e)
        {

            foreach (string skey in this.Request.QueryString.AllKeys)
            {
                StringParam += (skey + "=" + this.Request.QueryString[skey] + "&");
            }
            StringParam = StringParam + "remove=0&";
            StringParam = StringParam.Substring(0, StringParam.Length - 1);


            
            this.DBHelpName = DBHelperString.Dictionary;
            Page.DataBind();
             try
            {
                string loginName = this.Request.QueryString["userid"];
                string passwd = this.Request.QueryString["Md5PSWD"];
                string stime = this.Request.QueryString["sDateTime"];
                string loginId = this.Request.QueryString["userid"];
                string userID = SystemLoginComponent.GetUserIdByLoginId(loginId);
                string aurl = this.Request.QueryString["ActionUrl"];
                string PSWD = "BGPOAOCS" + stime;
                string Md5Value = GetMD5(PSWD, "");
                string ActionUrl = CreateActionUrl(aurl);
                 
                //if (string.IsNullOrEmpty(userID))
                //{
                //    return;
                //}

                if (Md5Value == passwd)
                {
                    //login in suc

                    //create the currentuser session

                    //传人真正的 userID
                    User currentUser = SystemLoginComponent.GetCurrentUser(userID);
                    //记录域密码
                    currentUser.Login_Pwd = passwd;
                    Session["CurrentUser"] = currentUser;
                    Session["OALoginUserID"] = currentUser.User_ID;
                    //更新用户的登录时间
                    SystemLoginComponent.UpdateUserLoginInfo(userID);

                    ////Get Authorities
                    //DataTable tblauth = dau.SelectAuthoritiesTableByUserID(userID);
                    //tblauth.PrimaryKey = new DataColumn[] { tblauth.Columns["AuthorityID"] };
                    //Session["AllAuthoritiesOfUser"] = tblauth;

                    OnlineUser ou = new OnlineUser();

                    #region 记录登录日志
                    ILogger log = UContainer.Resolve<ILogger>(Category.LoginLog);
                    log.Info(ou.GetLogInfo(currentUser.User_ID, Request.UserHostAddress, currentUser.User_Name,Request.Browser.Platform, Thread.CurrentThread.CurrentUICulture.Name, Request.Browser.Type));
                    #endregion

                    ou.CheckUserOnLine(
                         currentUser.SessionID, currentUser.User_ID, currentUser.Real_ID, currentUser.User_Name, currentUser.Login_ID, currentUser.Last_Login_Time, currentUser.This_Login_Time, currentUser.ORG_ID);

                    if (Request.QueryString["ReturnUrl"] != null && Request.QueryString["ReturnUrl"].ToString().ToLower().IndexOf("default.aspx") == -1 && Request.QueryString["ReturnUrl"].ToString().ToLower().IndexOf("logout.aspx") == -1)
                    {
                        FormsAuthentication.RedirectFromLoginPage(userID, false);
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(userID, false);
                        //string Url = String.Format("<script>window.open(\"../../Default.aspx\",'','toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=no,resizable=yes,menu=no,min=no,max=no');window.opener=null;window.open('','_top');window.top.close();</script>");
                        //Response.Write(Url);

                        //Modifid by 崔茂山 将打开子页面修改成直接跳转到页面 2010年9月17日15:18:40
                        Response.Redirect(String.Format("../../Default2.aspx{0}", StringParam));
                    }
                }
                else
                {
                    //this.lblErrorMessage.Text = GetString("InvalidUserOrPassword");
                    MessageShow.ShowMessageBox(this, GetString("InvalidUserOrPassword"));
                }

            }
             catch (System.Exception err)
             {
                 //LogNet.Error(Request.UserHostAddress, Request.Url.AbsolutePath, err);
                 //MessageShow.ShowMessageBox(this, GetString("UnkonwnError"));
                 MessageShow.ShowMessageBox(err.Message);
             }
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="sDataIn">需要加密的字符串</param>
        /// <param name="move">偏移量</param>
        /// <returns>sDataIn加密后的字符串</returns>
        public string GetMD5(string sDataIn, string move)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = System.Text.Encoding.UTF8.GetBytes(move + sDataIn);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string sTemp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                sTemp += bytHash[i].ToString("x").PadLeft(2, '0');
            }
            return sTemp;

        }
        /// <summary>
        /// 替换URL字符
        /// </summary>
        public string CreateActionUrl(string ActionUrl)
        {
            ActionUrl = ActionUrl.Replace("question", "?");
            ActionUrl = ActionUrl.Replace("equal", "=");
            ActionUrl = ActionUrl.Replace("with", "&");
            return ActionUrl;
        }
    }
}

